package utils

import (
	"os"
	"fmt"
	"errors"
	"context"

	"github.com/labstack/echo/v4"
	
	"github.com/ArtisanCloud/PowerLibs/v3/logger/drivers"
	"github.com/ArtisanCloud/PowerWeChat/v3/src/miniProgram"
	"github.com/ArtisanCloud/PowerWeChat/v3/src/kernel/power"
	"github.com/ArtisanCloud/PowerWeChat/v3/src/basicService/subscribeMessage/request"
	
)

const MiniProgramState = "trial" //小程序版本

const CourseAuditApprovedTmplID = "XE2jNqn98C7t--sq7DnJI63DnsLojVN3jgg7qA_Gr3Y"
const EnrollmentAuditApprovedTmplID = "aX_aHyTct-ZNKyOVM8GVup3tFRn1RDP3Io-Pqf6C8Hw"
const CourseStartTmplID = "uMu5jil9iUakgspa_ARgXEKYFIvrJCXzLGKFDwXPo7s"

func InitMnp() (*miniProgram.MiniProgram, error) {
	return miniProgram.NewMiniProgram(&miniProgram.UserConfig{
		AppID:     os.Getenv("MINIPROGRAM_APP_ID"), // 小程序、公众号或者企业微信的appid
		Secret:    os.Getenv("MINIPROGRAM_SECRET"), // 商户号 appID
		HttpDebug: false,
		Debug:     false,
		Log:  miniProgram.Log{
			Driver: &drivers.SimpleLogger{},
			Level:  "debug",
			// // 可以重定向到你的目录下，如果设置File和Error，默认会在当前目录下的wechat文件夹下生成日志
		  	// File:  "./info.log", 
		  	// Error: "./error.log",
			Stdout: true, //  是否打印在终端
		},
	})
}


// 发送课程审核通过的订阅消息
func CourseAuditApprovedSendMsg(c echo.Context, course_id int, openid, courseName, statusZh string) error {
	mnp, err := InitMnp()
	if err != nil {
		return errors.New("微信小程序初始化服务错误: " + err.Error())
	}

	fmt.Printf("课程 phrase5: %#v \n ", statusZh)
	data := &power.HashMap{
		"thing2": power.StringMap{
			"value": courseName,
		},
		"phrase5": power.StringMap{
			"value": statusZh,
		},
	}

	
	rs, err := mnp.SubscribeMessage.Send(c.Request().Context(), &request.RequestSubscribeMessageSend{
		ToUser:           openid,
		TemplateID:       CourseAuditApprovedTmplID,
		Page:             fmt.Sprintf("/pages/class/detail/detail?id=%d", course_id),
		MiniProgramState: MiniProgramState,
		Lang:             "zh_CN",
		Data:             data,
	})

	if err != nil {
		return err
	}
	fmt.Printf("课程（id %d）审核通过通知发送(openid:%s)结果:\n rs：%#v \n err: %#v\n", course_id, openid, rs, err)

	return nil
}

// 发送报名审核通过的订阅消息
func EnrollmentAuditApprovedSendMsg(c echo.Context, course_id int, openid, courseName, teacherName, startTime, addr,  statusZh string) error {
	mnp, err := InitMnp()
	if err != nil {
		return errors.New("微信小程序初始化服务错误: " + err.Error())
	}

	// fmt.Printf("%#v", openid)

	data := &power.HashMap{
		"thing1": power.StringMap{
			"value": courseName,
		},
		"name9": power.StringMap{
			"value": teacherName,
		},
		"date22": power.StringMap{
			"value": startTime,
		},
		"thing13": power.StringMap{
			"value": addr,
		},
		"thing11": power.StringMap{
			"value": statusZh,
		},
	}

	
	rs, err := mnp.SubscribeMessage.Send(c.Request().Context(), &request.RequestSubscribeMessageSend{
		ToUser:           openid,
		TemplateID:       EnrollmentAuditApprovedTmplID,
		Page:             fmt.Sprintf("/pages/class/detail/detail?id=%d", course_id),
		MiniProgramState: MiniProgramState,
		Lang:             "zh_CN",
		Data:             data,
	})

	if err != nil {
		return err
	}

	
	fmt.Printf("EnrollmentAuditApprovedSendMsg rs: %#v \n", rs)
	fmt.Printf("EnrollmentAuditApprovedSendMsg err: %#v \n", err)

	return nil
}

// 发送课程即将开始上课的订阅消息
func CourseStartSendMsg(c context.Context, course_id int, openid, courseName, teacherName, startTime, remark string) error {
	mnp, err := InitMnp()
	if err != nil {
		return errors.New("微信小程序初始化服务错误: " + err.Error())
	}

	data := &power.HashMap{
		"thing1": power.StringMap{
			"value": courseName,
		},
		"thing9": power.StringMap{
			"value": teacherName,
		},
		"time7": power.StringMap{
			"value": startTime,
		},
		"thing4": power.StringMap{
			"value": remark,
		},
	}

	
	rs, err := mnp.SubscribeMessage.Send(c, &request.RequestSubscribeMessageSend{
		ToUser:           openid,
		TemplateID:       CourseStartTmplID,
		Page:             fmt.Sprintf("/pages/class/detail/detail?id=%d", course_id),
		MiniProgramState: MiniProgramState,
		Lang:             "zh_CN",
		Data:             data,
	})

	if err != nil {
		return err
	}

	fmt.Printf("CourseStartSendMsg rs: %#v \n", rs)
	fmt.Printf("CourseStartSendMsg err: %#v \n", err)

	return nil
}
